/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the "Foxmon" extension for Firefox.
*
* The developer of the Original Code is Saravana Kumar.
*
* Portions created by the Initial Developer are 
* Copyright (C) 2006 the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*   Saravana Kumar <saravanannkl@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
* ***** END LICENSE BLOCK ***** */
var FoxmonReportGenerator = {
    
    ReportSqls: {
        HourlyTotalSql: "\
                        select	Hour, round(sum(HourlyPageVistTime)/60.0, 0) TotalDuration, \
                                round(sum(HourlyPageVistTime)/(count(*) * 60.0), 0) AverageDuration \
                        from (\
                            select Year, Month, Day, Hour, sum(PageVisitDuration) HourlyPageVistTime \
                            from BrowsingHistory \
                            /**********/ \
                            group by Year, Month, Day, Hour\
                        )\
                        group by Hour order by Hour;",
                        
       DailyTotalSql: "\
                        select Year, Month, Day, DayOfWeek, round(sum(PageVisitDuration)/60.0, 0) Time  \
                        from BrowsingHistory \
                        /**********/ \
                        group by Year, Month, Day \
                        order by Year, Month, Day;",

       HourlySql: "\
                    select Year, Month, Day, Hour, round(sum(PageVisitDuration)/60.0, 0) Time \
                    from BrowsingHistory \
                    /**********/ \
                    group by Year, Month, Day, Hour \
                    order by Year, Month, Day, Hour;"
        
    },

  	_buildQuery: function(sql, condn) {
	    var whereClause = '';
	    if(condn && condn.length>0) {
	        whereClause += "where ";
	        whereClause += condn[0][0] + " " + condn[0][1] + " " + condn[0][2];
	        for(var i=1; i<condn.length; i++) {
	            whereClause += "\r\n and ";
	            whereClause += condn[i][0] + " " + condn[i][1] + " " + condn[i][2];
	        }
	    }
        	    
	    return sql.replace("/**********/", whereClause);
	}, 
	
    GenerateReport : function () {
    
        var lstReports = document.getElementById("lstReports");
        var txtStartDate = document.getElementById("txtStartDate");
        var txtEndDate = document.getElementById("txtEndDate");
        var reportCondn = [];

        if(txtStartDate.value.length > 0) {
            reportCondn[reportCondn.length] = ["ID", ">", Date.parse(txtStartDate.value)];
        }

        if(txtEndDate.value.length > 0) {
            reportCondn[reportCondn.length] = ["ID", "<", (Date.parse(txtEndDate.value)+86400000)];
        }

        var lstDays = document.getElementById('lstDays');
        var selectedDays = [];
        
        for(var i=0;i<lstDays.selectedItems.length; i++) {
            selectedDays[selectedDays.length] = lstDays.selectedItems[i].value;
        }

        if(selectedDays.length>0) {
            reportCondn[reportCondn.length] = ["DayOfWeek", "in", "(" + selectedDays + ")"];
        }

        switch(lstReports.selectedItem.value) {
            case "1":
                //alert(sqlAppendCondition);
                //alert(reportCondn);
                var s = (new Date()).getTime();
                this.GenHourlyActivityReport(reportCondn);
                var e = (new Date()).getTime();
                alert((e-s));
                showReportsTab();
                break;
            default:
                alert("Select a report");
                break;
        }
    },
    
    GenHourlyActivityReport : function (reportCondn) {
        var HOURLY_RPT_COLUMNS = ["Year", "Month", "Day", "Day Of Week"];
        var WEEK_DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
        var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
        var browsingHours = [], dailyBrowsingHours = [];
        
        try {

            browsingHours = FoxmonStorageHelper.executeQuery(this._buildQuery(this.ReportSqls.HourlyTotalSql, reportCondn) );
            dailyBrowsingHours = FoxmonStorageHelper.executeQuery(this._buildQuery(this.ReportSqls.DailyTotalSql, reportCondn) );
            detailReport = FoxmonStorageHelper.executeQuery(this._buildQuery(this.ReportSqls.HourlySql, reportCondn) );
            
            var reportTree = document.createElement('tree');
            reportTree.id = "trHourlyReports";
            reportTree.flex = "1";
            reportTree.hidecolumnpicker = false;
            reportTree.setAttribute("enableColumnDrag", true);

            var reportColumns = document.createElement('treecols');
            Foxmon_createAndAppendXULElement(reportColumns, 'treecol', "tdReportHeaderCellDate", "Date with Weekday");
            var s = document.createElement("splitter");
            s.className = "tree-splitter";
            reportColumns.appendChild(s);
            s = null;
            
            for(var i=0; i<browsingHours.length; i++) {
                Foxmon_createAndAppendXULElement(reportColumns, 'treecol', "tdReportHeaderCell" + browsingHours[i][0], browsingHours[i][0]<12 ? browsingHours[i][0] +  " AM" :  (browsingHours[i][0]==12 ? 12 : browsingHours[i][0]-12) +  " PM");
                s = document.createElement("splitter");
                s.className = "tree-splitter";
                reportColumns.appendChild(s);
                s = null;
            }
            
            Foxmon_createAndAppendXULElement(reportColumns, 'treecol', "tdReportHeaderCellTotal", "Total Hours");
            s = document.createElement("splitter");
            s.className = "tree-splitter";
            reportColumns.appendChild(s);
            s = null;

            reportTree.appendChild(reportColumns);
            reportColumns = null;
            
            
            var reportTreeChildren = document.createElement('treechildren');

            for(var i=0; i<dailyBrowsingHours.length; i++) {
                var reportTreeItem = document.createElement('treeitem');
                var reportDataRow = document.createElement('treerow');
                var date = dailyBrowsingHours[i][0]+ "/" + dailyBrowsingHours[i][1] + "/" + dailyBrowsingHours[i][2];
                var recDate = (new Date(Date.parse(date)));
                var currentDateString =  MONTHS[recDate.getMonth()] + " " + recDate.getDate() + ", " + recDate.getFullYear() + " (" + WEEK_DAYS[recDate.getDay()] + ")";

                Foxmon_createAndAppendXULElement(reportDataRow, "treecell", "tdReportCellDate" + date, currentDateString);

                for(var j=0; j<browsingHours.length;j++)
		                Foxmon_createAndAppendXULElement(reportDataRow, "treecell", "tdReportCell" + date + "/" + browsingHours[j][0], "--");

                Foxmon_createAndAppendXULElement(reportDataRow, "treecell", "tdReportCellTotal-" + date, FoxmonHelper.ConvertDecimalHoursToHHMM(FoxmonHelper.Round(dailyBrowsingHours[i][4]/60.0)));
                reportTreeItem.appendChild(reportDataRow);
                reportTreeChildren.appendChild(reportTreeItem);
                reportDataRow = null;
                reportTreeItem = null;
            }
            
            var reportDataTotalDurationRow = document.createElement('treerow');
		    var reportDataAvgDurationRow = document.createElement('treerow');

		    Foxmon_createAndAppendXULElement(reportDataTotalDurationRow, "treecell", "tdReportCellTotalDuration", "Total Time");
		    Foxmon_createAndAppendXULElement(reportDataAvgDurationRow, "treecell", "tdReportCellAvgDuration", "Average Time");
            var totalTime = 0;
            for(var i=0; i<browsingHours.length; i++) {
                Foxmon_createAndAppendXULElement(reportDataTotalDurationRow, "treecell", "tdReportCellTotalDuration" + browsingHours[i][0], browsingHours[i][1]);
                totalTime += browsingHours[i][1];
                Foxmon_createAndAppendXULElement(reportDataAvgDurationRow, "treecell", "tdReportCellAvgDuration" + browsingHours[i][0], browsingHours[i][2]);
            }
		    Foxmon_createAndAppendXULElement(reportDataTotalDurationRow, "treecell", "tdReportCellTotalDurationTotalTime", FoxmonHelper.ConvertDecimalHoursToHHMM(FoxmonHelper.Round(totalTime/60.0)));
		    Foxmon_createAndAppendXULElement(reportDataAvgDurationRow, "treecell", "tdReportCellTotalAvgDuration", FoxmonHelper.ConvertDecimalHoursToHHMM(FoxmonHelper.Round(totalTime/(dailyBrowsingHours.length * 60.0))));
		    
		    var reportDataTotalDurationRowContainer = document.createElement('treeitem');
		    var reportDataAvgDurationRowContainer = document.createElement('treeitem');
		    reportDataTotalDurationRowContainer.appendChild(reportDataTotalDurationRow);
		    reportDataAvgDurationRowContainer.appendChild(reportDataAvgDurationRow);

		    reportTreeChildren.appendChild(reportDataTotalDurationRowContainer);
		    reportTreeChildren.appendChild(reportDataAvgDurationRowContainer);

		    reportDataTotalDurationRow = null;
		    reportDataAvgDurationRow = null;


		    reportTree.appendChild(reportTreeChildren);
		    reportTreeChildren = null;

		    var reportHolder = document.getElementById('hbxHourlyReports');
                    while(reportHolder.firstChild) reportHolder.removeChild(reportHolder.firstChild);
		    reportHolder.appendChild(reportTree);
		    
            for(var i=0;i<detailReport.length;i++) {
                var id = "tdReportCell" + detailReport[i][0] + "/" + detailReport[i][1] + "/" + detailReport[i][2] + "/" + detailReport[i][3];
                var time = detailReport[i][4];
                var tdReportCell = document.getElementById(id);
                if(tdReportCell) {
                    tdReportCell.setAttribute("label", time);
                    //if(time>15) tdReportCell.className = "highlight";
                }
                else {
                    FoxmonLogger.Log("Missing Cell with ID: " + id);
                }
            }
        }
        catch(ex) {
            FoxmonLogger.LogError(ex);
        }
    }
}
function Foxmon_generateDailyBrowsingReport(sqlAppendCondition) {
}

function Foxmon_createAndAppendTableCell(row, id, innerHTML) {
	Foxmon_createAndAppendChild(row, "td", id, innerHTML);
}

function Foxmon_createAndAppendChild(parent, childTagName, id, innerHTML) {
	var childNode = document.createElement(childTagName);
	childNode.id = id;
	childNode.innerHTML = innerHTML;
	parent.appendChild(childNode);
	childNode = null;
}

function Foxmon_createAndAppendXULElement(parent, childTagName, id, label, flex) {
	var childNode = document.createElement(childTagName);
	if(!flex) flex = "1";
	childNode.id = id;
	childNode.setAttribute("label", label);
	childNode.flex = flex;
	//childNode.sortActive = false;
	parent.appendChild(childNode);
	childNode = null;
}